<?php

namespace Temu;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class TmClient
{
    public $appkey;

    public $appSecret;

    public $gatewayUrl;

    private $GuzzleHttpClient;

    /**
     * @param $url
     * 正式环境 CN https://openapi.kuajingmaihuo.com/openapi/router
     * 测试环境 CN https://kj-openapi.temudemo.com/openapi/router
     * 正式环境 US https://openapi-b-us.temu.com/open/router
     * 测试环境 US http://openapi-b-us.temudemo.com/open/router
     * @param $appkey
     * @param $secretKey
     */
    public function __construct($url = "", $appkey = "", $appSecret = "")
    {
        $length = strlen($url);
        if ($length == 0) {
            throw new \Exception("url is empty", 0);
        }
        $this->gatewayUrl = $url;
        $this->appkey = $appkey;
        $this->appSecret = $appSecret;
        $this->GuzzleHttpClient=new Client();
    }

    protected function generateSign($params)
    {
        ksort($params);

        $stringToBeSigned = $this->appSecret;
        foreach ($params as $k => $v) {
            $stringToBeSigned .= "$k$v";
        }
        unset($k, $v);
        $stringToBeSigned.=$this->appSecret;
        return strtoupper(md5($stringToBeSigned));
    }
    public function execute(TmRequest $request, $accessToken = null)
    {
        $sysParams["type"] = $request->apiType;
        $sysParams['app_key']=$this->appkey;
        $sysParams['timestamp']=time();
        // $sysParams["sign"] = $this->signMethod;
        $sysParams["data_type"] = 'JSON';
        $sysParams["access_token"] = $accessToken;
       // $sysParams["version"] = 'V1';
        $apiParams = $request->udfParams;

        $requestUrl = $this->gatewayUrl;

        if ($this->endWith($requestUrl, "/")) {
            $requestUrl = substr($requestUrl, 0, -1);
        }

//		$requestUrl .= $request->apiName;
        $requestUrl .= '?';

//        foreach ($apiParams as $apiParamKey => $apiParamValue)
//        {
//            $requestUrl .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
//        }
        $sysParams=array_merge($sysParams,$apiParams);

        unset($apiParams);
        $sysParams["sign"] = $this->generateSign($sysParams);
        $resp='';
        $resp= $this->GuzzleHttpClient->post($requestUrl,[
            RequestOptions::BODY=>json_encode($sysParams),
            RequestOptions::HEADERS=>[
                'content-type'=>'application/json'
            ]
        ]);
        if($resp->getStatusCode()==200){
            $result=json_decode($resp?->getBody()?->getContents());
            if($result->success){
                return $result->result??['status'=>'success'];
            }else{
                throw new ResponseException(json_encode(['msg'=>$result->errorMsg,'requestId'=>$result->requestId]),$result->errorCode);
            }
        }else{
            throw new \Exception("request failed", 0);
        }
    }
    function endWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return false;
        }
        return (substr($haystack, -$length) === $needle);
    }

}
